package com.xwaf.platform.web.controller.x;

import java.io.IOException;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.xwaf.platform.common.api.CommonResponse;
import com.xwaf.platform.common.api.constants.BusinessConstants;
import com.xwaf.platform.common.api.entity.AttachmentInfo;
import com.xwaf.platform.common.web.BaseController;
import com.xwaf.platform.web.util.OSSManageUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

@ApiIgnore
@RestController
@Api(tags = "文件上传", hidden = true)
@RequestMapping(value = "/x/file")
public class FileUploadController extends BaseController {

	@Autowired
	private OSSManageUtil ossUtil;

	@ApiOperation("文件上传")
	@RequestMapping(value = "/upload", produces = "application/json;charset=UTF-8")
	public CommonResponse list(@RequestParam("file") MultipartFile file,
			@RequestParam(value = "reName", required = false) String reName) throws IOException, Exception {
		// StandardServletMultipartResolver resolver = new StandardServletMultipartResolver();
		// MultipartHttpServletRequest multipartRequest = resolver.resolveMultipart(request);
		// MultipartFile file = multipartRequest.getFile("file");
		if (file.isEmpty()) {
			CommonResponse.createCustomCommonResponse(BusinessConstants.FILE_ISEMPTY.getCode(),
					BusinessConstants.FILE_ISEMPTY.getMsg());
		}
		// 获取文件名
		String fileName = file.getOriginalFilename();
		// 获取文件扩展名
		String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
		String filePath = "";
		// reName=1 重命名 ,0不重命名
		if (StringUtils.isNotEmpty(reName) && "0".equals(reName)) {
			filePath = ossUtil.uploadFile(file.getInputStream(), file.getSize(), fileName);
		} else {
			// 文件重命名
			String reFileName = UUID.randomUUID().toString() + "." + suffix;
			logger.info("上传的文件名为：" + fileName + ",重命名后：" + reFileName);
			filePath = ossUtil.uploadFile(file.getInputStream(), file.getSize(), reFileName);
		}
		AttachmentInfo atta = new AttachmentInfo();
		atta.setName(fileName);
		atta.setFileSize(file.getSize());
		atta.setFileUrl(filePath);
		atta.setContentType(suffix);
		return CommonResponse.createCommonResponse(atta);
	}
}